import { logout, login, getInfo, menubyuser } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(), // getToken(),
  name: '',
  roles: [],
  menus: [],
  urlSet: [],
  adminInfo: {},
  userId: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_URLSET: (state, urlSet) => {
    state.urlSet = urlSet
  },
  SET_ADMININFO: (state, adminInfo) => {
    state.adminInfo = adminInfo
  }
}
const getters = {
  getdeptId(state) {
    return state.deptId
  },
  getuserdata(state) {
    return state.userdata
  }
}

const actions = {
  login({ commit }, userInfo) {
    const { userName, passWord } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: userName.trim(), passWord: passWord, systemFlag: 23 })
        .then(response => {
          const data = response.data
          const tokenStr = data
          if (tokenStr) {
            setToken(tokenStr)
            commit('SET_TOKEN', tokenStr)
            resolve()
          } else {
            Vue.prototype.$message.error(response.message)
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(response => {
          const data = response.data
          const { roles, menus, admin } = data
          commit('SET_NAME', admin.username)
          commit('SET_USERID', admin.userId)
          commit('SET_ADMININFO', admin)
          commit('SET_URLSET', admin.urlSet)
          commit('SET_MENUS', menus)
          commit('SET_ROLES', JSON.parse(JSON.stringify(admin.urlSet)))
          // commit('SET_ROLES', roles)
          resolve(data)
          window.localStorage.setItem('authUrl', JSON.stringify(response.data.admin.urlSet))
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_NAME', '')
          removeToken()
          resetRouter()
          dispatch('tagsView/delAllViews', null, { root: true })
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_NAME', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
